package top.jfunc.validation.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by ZhangGang on 2017/9/26.
 */
public class ReflectUtil {

    public static Set<Field> getFieldsByClass(Class cls) {
        Set<Field> fieldSet = new HashSet<>();
        for (Class<?> clazz = cls; clazz != Object.class; clazz = clazz.getSuperclass()) {
            Field[] fields = clazz.getDeclaredFields();
            if (NullUtil.isNull(fields)) {
                continue;
            }
            for (Field field : fields) {
                if (!field.getName().equals("class") && !field.getName().equals("serialVersionUID")) {
                    fieldSet.add(field);
                }
            }
        }
        return fieldSet;
    }

    /**
     * 根据属性名获取属性值
     * @param ob 对象
     * @param fieldName 属性名
     * @return 属性值
     */
    public static Object get(Object ob, String fieldName) {
        try {
            //第一个字母转大写
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            //获取get方法名
            String getter = "get" + firstLetter + fieldName.substring(1);
            //获取get方法
            Method method = ob.getClass().getMethod(getter);
            //执行get方法获取属性值
            return method.invoke(ob);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static Object getFieldValue(Object o , Field field) {
        try {
            field.setAccessible(true);
            return field.get(o);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
